﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace FSM
{
    public class StateMachine:MonoBehaviour
    {
        private HashSet<StateNode> states = new HashSet<StateNode>();
        private string nextStateName;
        private StateNode currentState;
        private bool hasChange = false;
        public StateNode FindState(string name)
        {
            foreach(var item in states)
            {
                if(item.name == name)
                {
                    return item;
                }
            }
            return null;
        }
        public void AddState(StateNode node)
        {
            states.Add(node);
        }
        public void ChangeStateByName(string stname)
        {
            nextStateName = stname;
            hasChange = true;
            if(currentState)
            {
                currentState.Leave();
            }
        }
        public void Update()
        {
            if(hasChange)
            {
                var nextState = FindState(nextStateName);
                //nextState.Enter();
                currentState = nextState;
				if(currentState != null)
				{
					currentState.Enter();
				}
                hasChange = false;
            }
            if(currentState)
            {
                currentState.Update();
            }
        }
    }
}
